<?php
/**
 * CustomfieldsController.php
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to version 2.0 of the Apache license
 * that is available through the world-wide-web at the following URI:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * @category Controller
 * @package  Controller
 * @author   Alex Kopp <koppa@rpi.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link     http://http://code.google.com/p/tri-chi/
 */

/**
 * CustomfieldsController
 *
 * The controller that manages the custom fields for PNMs
 *
 * @category Controller
 * @package  Controller
 * @author   Alex Kopp <koppa@rpi.edu>
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link     http://http://code.google.com/p/tri-chi/
 */
class CustomfieldsController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/main';

    /**
     * Filters
     * 
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * 
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
        array('allow',
            'actions'=>array('index','create','update','delete','admin', 'view'),
            'roles'=>array('admin'),
        ),
        array('deny',
            'users'=>array('*'),
        ),
        );
    }

    /**
     * Displays a particular model.
     * 
     * @param integer $id the ID of the model to be displayed
     * 
     * @return void
     */
    public function actionView($id)
    {
        $this->render('view', array('model'=>$this->loadModel($id),));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * 
     * @return void
     */
    public function actionCreate()
    {
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * 
     * @param integer $id the ID of the model to be updated
     * 
     * @return void
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Customfields'])) {
            $model->attributes=$_POST['Customfields'];
            if ($model->save()) {
                $this->redirect(array('view','id'=>$model->id));
            }
        }

        $this->render('update', array('model'=>$model,));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * 
     * @param integer $id the ID of the model to be deleted
     * 
     * @return void
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            
            //Must Delete All of it's Custom Information Field Values First
            //due to foreign key restrictions
            $mCIFV = Customfieldvalues::model()->findAll('custom_field_id =:cfid', array(':cfid'=> $id));
            foreach ($mCIFV as $cifv) {
                $cifv->delete();
            }
            
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax'])) {
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    /**
     * Lists all models.
     * 
     * @return void
     */
    public function actionIndex()
    {
        $model=new Customfields('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Customfields'])) {
            $model->attributes=$_GET['Customfields'];
        }
        
        $newModel=new Customfields;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Customfields'])) {
            $newModel->attributes=$_POST['Customfields'];
            if ($newModel->save()) {
                $this->redirect(array('view','id'=>$newModel->id));
            }
        }

        $this->render('index', array('model'=>$model,'newModel'=>$newModel));        
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * 
     * @param integer $id the ID of the model to be loaded
     * 
     * @return model $model
     */
    public function loadModel($id)
    {
        $model=Customfields::model()->findByPk($id);
        if ($model===null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * 
     * @param CModel $model the model to be validated
     * 
     * @return void
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax']==='customfields-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
